package com.agree.parse;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

import com.agree.MyPanel;

/**
 * 
 * @author admin
 *
 */
public class ParseData{
	
	private int readBannerBytes = 0;
	private int bannerLength = 2;
	
	private int readFrameBytes = 0;
	private int frameBodyLength = 0;
	
	private ByteArrayOutputStream out = new ByteArrayOutputStream();
	
	Banner banner = new Banner();
	
	public  void server() {
		Socket sk = new Socket();
		SocketAddress socketAddress = new InetSocketAddress("127.0.0.1",1717);
		try {
			sk.connect(socketAddress);
			
			InputStream in = sk.getInputStream();
			byte[] b = new byte[65536];
			int len = -1;
			while((len = in.read(b))!=-1) {
				info("chunk(length=%d)", len);
			    readData(b, len);
			}
			sk.close();
		} catch (IOException e) {
		
			e.printStackTrace();
		}
	}
	
	
	
	public void readData(byte[] chunk,int len) {
		
		for ( int cursor = 0;cursor < len;) {
			 if (readBannerBytes < bannerLength) {
				 switch (readBannerBytes) {
			          case 0:
			            // version
			            banner.version = chunk[cursor];
			            break;
			          case 1:
			        	banner.length = bannerLength = chunk[cursor];
			        	 break;
			          case 2:
			          case 3:
			          case 4:
			          case 5:
			            // pid
			            banner.pid +=
			              (chunk[cursor] << ((readBannerBytes - 2) * 8)) >>> 0;
			            break;
			              case 6:
			              case 7:
			              case 8:
			              case 9:
			                // real width
			                banner.realWidth +=
			                  (chunk[cursor] << ((readBannerBytes - 6) * 8)) >>> 0;
			                break;
			              case 10:
			              case 11:
			              case 12:
			              case 13:
			                // real height
			                banner.realHeight +=
			                  (chunk[cursor] << ((readBannerBytes - 10) * 8)) >>> 0;
			                break;
			              case 14:
			              case 15:
			              case 16:
			              case 17:
			                // virtual width
			                banner.virtualWidth +=
			                  (chunk[cursor] << ((readBannerBytes - 14) * 8)) >>> 0;
			                break;
			              case 18:
			              case 19:
			              case 20:
			              case 21:
			                // virtual height
			                banner.virtualHeight +=
			                  (chunk[cursor] << ((readBannerBytes - 18) * 8)) >>> 0;
			                break;
			              case 22:
			                // orientation
			                banner.orientation += chunk[cursor] * 90;
			                break;
			              case 23:
			                // quirks
			                banner.quirks = chunk[cursor];
			                break;
				 }
				  cursor += 1;
		          readBannerBytes += 1;

		          if (readBannerBytes == bannerLength) {
		          // System.out.println(banner);
		          }
			 }else if (readFrameBytes < 4) {
		          frameBodyLength += ((chunk[cursor] & 0xFF) << (readFrameBytes * 8)) >>> 0;
	              cursor += 1;
	              readFrameBytes += 1;
	              info("headerbyte%d(val=%d)", readFrameBytes, frameBodyLength);
            }else {
            	if (len - cursor >= frameBodyLength) {
            		
                    info("bodyfin(len=%d,cursor=%d)", frameBodyLength, cursor);

//                    frameBody = Buffer.concat([
//                      frameBody
//                    , chunk.slice(cursor, cursor + frameBodyLength)
//                    ])
                    
                    try {
						out.write(chunk,cursor,cursor + frameBodyLength);
					} catch (Exception e) {
						e.printStackTrace();
					}
                    

                  
                    byte[] frameBody = out.toByteArray();
                   
                    // Sanity check for JPG header, only here for debugging purposes.
//                    if (frameBody[0] != -1 || frameBody[1] != 216) {
//                      return ;
//                    }

                    // 通知读取完毕
//                    ws.send(frameBody, {
//                      binary: true
//                    })
                  //  System.out.println(1);
                //    pcs.firePropertyChange("image",null,frameBody);                  
                    add(frameBody);                 
                    // 清理操作
                    cursor += frameBodyLength;
                    frameBodyLength = readFrameBytes = 0;
                    out.reset();
                  }
                  else {
                    info("body(len=%d)", len - cursor);
                    
                    try {
						out.write(chunk,cursor,len-cursor);
					} catch (Exception e) {
						e.printStackTrace();
					}
                    
                    frameBodyLength -= len - cursor;
                    readFrameBytes += len - cursor;
                    cursor = len;
                 }
            }
        }
	}
	
	public void add(byte[] e) {
		MyPanel.queue.add(e);
	}
	
	public static void info(String str, Object... obj) {
		// System.out.println(String.format(str, obj));
	}
    
    public class Banner {
    	
    	private int version;
    	
    	private int length;
    	
    	private int pid;
    	
    	private int realWidth;
    	
    	private int realHeight;
    	
    	private int virtualWidth;
    	
    	private int virtualHeight;
    	
    	private int orientation;
    	
    	private int quirks;
	
    	public String toString() {
    		StringBuffer sb = new StringBuffer();
    		sb.append("banner { \n");
    		sb.append("  version: "+version+"\n");
    		sb.append("  length: "+length+"\n");
    		sb.append("  pid: "+pid+"\n");
    		sb.append("  realWidth: "+realWidth+"\n");
    		sb.append("  realHeight: "+realHeight+"\n");
    		sb.append("  virtualWidth: "+virtualWidth+"\n");
    		sb.append("  virtualHeight: "+virtualHeight+"\n");
    		sb.append("  orientation: "+orientation+"\n");
    		sb.append("  quirks: "+quirks+"\n");
    		sb.append("}");	
    		return sb.toString();
    	}
    }
}
